<template>
	<view class="uni-header">
	<uni-breadcrumb separator="/">
		<uni-breadcrumb-item v-for="(route,index) in routes" :key="index" :to="route.to">
			{{route.name}}
		</uni-breadcrumb-item>
	</uni-breadcrumb>

	</view>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind" :label-width="100">
			<uni-forms-item name="shop_id" label="所属店铺" required>
				<uni-easyinput disabled="true" placeholder="所属店铺" v-model="store"></uni-easyinput>
			</uni-forms-item>
			<uni-easyinput style="display:none;" disabled="true" placeholder="店铺id，参考shop表"
				v-model="formData.shop_id"></uni-easyinput>
			<uni-forms-item name="goods_sn" label="货号" required>
				<uni-easyinput placeholder="商品的唯一货号" disabled v-model="formData.goods_sn" trim="both"></uni-easyinput>
			</uni-forms-item>
			
			<uni-forms-item name="category_id" label="商品分类" required>
				<uni-data-picker v-model="formData.category_id" collection="shop-categories"
					:where="`shop_id=='${store_id}'`" orderby="sort asc"
					field="_id as value,title as text"></uni-data-picker>
			</uni-forms-item>
			
			<uni-forms-item name="name" label="名称" required>
				<view style="display:flex; align-items:center;">
					<uni-easyinput placeholder="请输入商品名称,最少2个汉字,最多30个汉字" v-model="formData.name" trim="both"></uni-easyinput>
					<button style="margin:0 5px;padding:2.5px 20px;" size="mini" @click="clcikSearch" type="primary">
						查相似
					</button>
				</view>
			</uni-forms-item>
			
			<!-- 类似商品列表 -->
			<div class="similar_goods" v-if="showSimilarGoods">
				<div class="similar_goods_title">
					<div class="similar_goods_title_fixed">
						<text>
							选择相似商品可快速添加
						</text>
						<text>
							<uni-icons type="close" style="cursor: pointer;" @click="this.showSimilarGoods=false" size="30" color="#6a6a6a"></uni-icons>
						</text>
					</div>
				</div>
				<view class="similar_goods_body">
					<view class="grid">
						<view class="item_box" v-for="(item,index) in similarGoodsData"  @click="handleItemClick(item)" >
							<view>
								<image class="slot-image"  :src="item.images[0].url + '?x-oss-process=image/resize,m_fixed,h_200,w_200'"  mode="widthFix"></image>
							</view>
							<view class="title">
								{{item.name}}
							</view>
							<view class="label">
								{{item.ingredients}}
							</view>
						</view>
					</view>
					<span class="null_status" v-if="similarGoodsData.length==0"  >
						<uni-icons type="search" size="20"></uni-icons>
						<view class="" style="font-size:10px;color:#999;">
							暂无搜索内容
						</view>
					</span>
				</view>
				<view class="loadingMore"    >
					<view v-if="skip>39" style="" class="loadingMore" @click="clcikSearch(102)" >
						<text>返回上一批</text>
						<uni-icons type="loop" color="#44444462" size="20"></uni-icons>
					</view>
					<view class="loadingMore"  @click="clcikSearch(101)" v-if="similarGoodsData.length>39 " >
						<text>换一批</text>
						<uni-icons type="loop" color="#44444462" size="20"></uni-icons>
					</view>
				</view>
			</div>
			
			<uni-forms-item name="feature" label="特色">
				<uni-easyinput placeholder="选填，比如：“新品/招牌”" v-model="formData.feature"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="ingredients" label="主料">
				<uni-easyinput placeholder="请输入商品主料，比如：“田螺”" v-model="formData.ingredients"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="accessories" label="辅料">
				<uni-easyinput placeholder="请输入商品辅料，比如：“花椒，盐，豆瓣酱，蒜，干辣椒”" v-model="formData.accessories"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="description" label="详细描述">
				<uni-easyinput placeholder="商品详细描述,500个汉字以内" type="textarea" v-model="formData.description"
					trim="both"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="images" label="商品照片" required>
				<uni-file-picker file-mediatype="image" file-extname="jpg,png,gif" :limit="50" return-type="array"
					v-model="formData.images"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="sku" label="规格">
				<uni-easyinput placeholder="可在这里输入自定义规格标题,如:规格/份量,默认为:规格" v-model="formData.sku.title"></uni-easyinput>
				<view class="add-goods-sku">
					<uni-table border stripe>
						<uni-tr>
							<uni-th width="100" align="center">标题</uni-th>
							<uni-th width="50" align="center">价格</uni-th>
							<uni-th width="50" align="center">操作</uni-th>
						</uni-tr>
						<uni-tr v-for="(item,index) in formData.sku.attr">
							<uni-td>
								<uni-easyinput placeholder="属性名称" v-model="formData.sku.attr[index].title"></uni-easyinput>
							</uni-td>
							<uni-td><uni-easyinput type="number" placeholder="价格"
									v-model="formData.sku.attr[index].price"></uni-easyinput></uni-td>
							<uni-td>
								<label class="goods-add-sku-del" @click="delSku(index)">删除</label>
							</uni-td>
						</uni-tr>
						<uni-tr>
							<uni-td colspan="3" align="center" style="cursor: pointer;" @click="addSku()">+
								增加一项</uni-td>
						</uni-tr>
					</uni-table>
				</view>

			</uni-forms-item>


			<uni-forms-item name="goods_options" label="属性" v-for="(item,index) in formData.goods_options">
				<uni-easyinput placeholder="可在这里输入自定义选项标题,如:辣度/口味/热度,默认为:口味"
					v-model="formData.goods_options[index].title"></uni-easyinput>
				<view class="add-goods-sku">
					<uni-table border stripe>
						<uni-tr>
							<uni-th width="100" align="center">标题</uni-th>
							<uni-th width="50" align="center">操作</uni-th>
						</uni-tr>
						<uni-tr v-for="(items,indexs) in formData.goods_options[index].attr">
							<uni-td>
								<uni-easyinput placeholder="请输入标题"
									v-model="formData.goods_options[index].attr[indexs]"></uni-easyinput>
							</uni-td>
							<uni-td>
								<label class="goods-add-sku-del" @click="delOptions(index,indexs)">删除</label>
							</uni-td>
						</uni-tr>
						<uni-tr>
							<uni-td colspan="3" align="center" style="cursor: pointer;" @click="addOptions(index,indexs)">+
								增加一项</uni-td>
						</uni-tr>
					</uni-table>
				</view>

			</uni-forms-item>
			<view class="goods-add-attr" @click="addAttr()"> + 新增属性</view>

			<uni-forms-item name="other_price" label="到店价">
				<uni-easyinput placeholder="请输入到店价" @change="setPrice()" type="text"
					v-model="formData.other_price"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="price" label="现价" required>
				<uni-easyinput placeholder="请输入商品现价" type="text" v-model="formData.price"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="group_price" label="团派优惠" required>
				<uni-easyinput placeholder="请输入团派优惠价" type="text" v-model="formData.group_price"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="weight" label="重量">
				<uni-easyinput placeholder="请输入商品重量" type="text" v-model="formData.weight"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="initial_purchase" label="起购数量">
				<uni-easyinput placeholder="请输入起购数量,最少为1" type="number" v-model="formData.initial_purchase"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="pack_price" label="打包费">
				<uni-easyinput placeholder="请输入打包费" type="text" v-model="formData.pack_price"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="is_index" label="是否首页推荐">
				<switch :checked="formData.is_index"   style="transform:scale(0.9)" @change="changeIsIndex" />
			</uni-forms-item>
			<uni-forms-item name="special" label="设置零元购">
				<switch :checked="formData.special"   style="transform:scale(0.9)" @change="changeIsSpecial" />
			</uni-forms-item>
			<uni-forms-item name="mandatoy" label="商品必点">
				<switch :checked="formData.mandatoy"   style="transform:scale(0.9)" @change="changeIsMandatoy" />
			</uni-forms-item>
			<uni-forms-item name="is_shelf" label="上下架">
				<switch :checked="formData.is_shelf"   style="transform:scale(0.9)" @change="changeIsShelf" />
			</uni-forms-item>
			<!-- <uni-forms-item name="delivery_price" label="配送费">
 			<uni-easyinput placeholder="请输入配送费" type="text" v-model="formData.delivery_price"></uni-easyinput>
 		</uni-forms-item> -->



			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 150px;" @click="submit(2)">提交修改</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>
<script>
	import {
		validator
	} from '../../../js_sdk/validator/goods.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'goods';
	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}
	export default {
		data() {
			let formData = {
				"category_id": "",
				"shop_id": "",
				"goods_sn": "",
				"create_uid":'',
				"create_date":0,
				"name": "",
				"feature": '',
				"ingredients": "",
				"accessories": "",
				"description": "",
				"images": [],
				"sku": {
					title: '',
					attr: [{
						title: '',
						price: ''
					}]
				},
				"goods_options": [{
					title: '',
					attr: ['']
				}],
				"price": '',
				"weight": '',
				"other_price": '',
				"initial_purchase": 1,
				"pack_price": 0,
				"delivery_price": 0,
				"is_index":false,
				"special":0,
				"mandatoy":false,
				"is_shelf":true
			}
			return {
				// 面包屑
				routes: [
					{to: "/pages/index/index",name: "首页",},
					{to: "",name: "店铺管理",},
					{to: "/pages/shop/goods/goods",name: "商品管理"},
					{to: "",name: "修改商品",},
				],
				showSimilarGoods: false, // 展示框-相似商品
				similarGoodsData:[],
				formData,
				store: '', //店铺名称
				store_id: '', //店铺id
				formOptions: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			var that = this;
			uni.getStorage({
				key: 'uni-id-pages-userInfo',
				success: function(res) {
					that.formData.create_uid = res.data._id;
				}
			})
			if (e.id) {
				this.store = e.store;
				this.store_id = e.store_id;
				this.formData.shop_id = e.store_id;
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			//设置价格
			setPrice() {
				this.formData.price = parseFloat(this.formData.other_price * 0.9);
			},
			// 搜索商品-按钮
			clcikSearch(bool) {
				if(bool==101){
					this.skip += 40
				}else if (bool == 102) {
					this.skip -= 40
				} else {
					this.skip = 0
				}
				this.showSimilarGoods = true
				var nameVal = this.formData.name
				var Field = "name,_id,images,ingredients,special,mandatoy,description,group_price,sku,goods_options,accessories,other_price,price,weight,month_sales,total_sales,initial_purchase,pack_price,delivery_price"
				// 构建查询对象
				let query = {}; 
				// 构建搜索条件
				let search = {
					$or: [
						/*- 搜索可根据商品名称、主料、辅料、规格名称、属性属性名称进行模糊匹配*/
						{
							'name': {$regex: '.*' + nameVal + '.*',$options: 'i'}// 使用正则表达式进行模糊匹配，不区分大小写
						},
						{
							'ingredients': {$regex: '.*' + nameVal + '.*',$options: 'i'},
						},
						{
							'accessories': {$regex: '.*' + nameVal + '.*',$options: 'i'},
						},
						{
							'sku.title': {$regex: '.*' + nameVal + '.*',$options: 'i'},
						},
						{
							'sku.attr.title': {$regex: '.*' + nameVal + '.*',$options: 'i'},
						},
						{
							'sku.goods_options.title': {$regex: '.*' + nameVal + '.*',$options: 'i'}
						}
					]
				};
				// 合并查询条件
				// Object.assign(query, search); // 将搜索条件合并到查询对象中
				console.log(Object.assign(query, search));
				db.collection(dbCollectionName).where(query).field(Field).skip(this.skip).limit(40).get({
					getOne: false
				}).then(res => {
					this.similarGoodsData = res.result.data
				})
			},
			// 点击整个元素
			handleItemClick(item){
				this.formData.images =  [...this.formData.images,...item.images]
				this.formData.accessories = item.accessories
				this.showSimilarGoods = false
			},
			// 是否开启首页展示
			changeIsIndex(e){
				// console.log(e.detail.value);
				this.formData.is_index = e.detail.value
			},
			changeIsSpecial(e){
				let val = e.detail.value
				val = val ? 1 : 0
				this.formData.special = val
			},
			changeIsMandatoy(e){
				let val = e.detail.value
				this.formData.mandatoy = val
			},
			// 是否上架
			changeIsShelf(e){
				this.formData.is_shelf = e.detail.value
			},
			//新增属性
			addAttr() {
				this.formData.goods_options.push({
					title: '',
					attr: ['']
				});
			},
			//增加选项的其中一项
			addOptions(index, indexs) {
				this.formData.goods_options[index].attr.push('');
			},
			//删除选项的其中一项
			delOptions(index, indexs) {
				this.formData.goods_options[index].attr.splice(indexs, 1);
			},
			//删除一项sku
			delSku(index) {
				this.formData.sku.attr.splice(index, 1);
			},
			//增加一项sku
			addSku() {
				this.formData.sku.attr.push({
					title: '',
					price: ''
				});
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					res.sku = this.formData.sku;
					res.goods_options = this.formData.goods_options;
					res.other_price = parseInt(res.other_price * 100);
					res.price = parseInt(Math.ceil(res.price * 100));
					res.group_price = parseInt(Math.ceil(res.group_price * 100));
					res.pack_price = parseInt(res.pack_price * 100);
					res.delivery_price = res.delivery_price ?  parseInt(res.delivery_price * 100 ) : 0 ;
					//把sku价格乘以100，以分计算
					res.sku.attr.map(function(item, index) {
						return item.price = parseInt(item.price * 100);
					});
					 // console.log(res);
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				value.create_uid = uni.getStorageSync("uni-id-pages-userInfo")._id
				value.create_date = Date.now()
				// console.log(value);
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title:'‘'+value.name+'’'+'修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"category_id,shop_id,goods_sn,name,is_index,special,mandatoy,is_shelf,weight,initial_purchase,ingredients,accessories,month_sales,total_sales,description,images,goods_options,price,group_price,delivery_price,feature,pack_price,other_price,comment_total,sku,create_uid,create_date"
					).get({getOne:true}).then((res) => {
					const data = res.result.data
					if (data) {
						data.price = data.price / 100;
						data.other_price = data.other_price / 100;
						data.pack_price = (data.pack_price / 100).toString();
						data.group_price = (data.group_price / 100).toString();
						data.delivery_price = (data.delivery_price?data.delivery_price / 100:0).toString();
						
						//把sku价格乘以100，以分计算
						data.sku.attr.map(function(item, index) {
							return item.price = item.price / 100;
						});
						// console.log('商品信息', data);
						
						this.formData = data

					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.loadingMore{
		display: flex;
		justify-content:center;
		align-items:center;
		margin:5px;
		font-size:18px;
		padding:0px 0;
		cursor:pointer;
		color:#2b2b2b62;
		text{
			margin:0 3px
		}
	}
	.slot-image{
		width:150px;
		height: 150px;
		margin:0 30px;
	}
	.null_status {
		display: flex;
		justify-content: center;
		padding: 20px 0;
		margin: 0 auto;
	}
	.grid{
		padding:60rpx 0 0 0; 
		display:grid;
		grid-template-columns:1fr 1fr 1fr 1fr;
		grid-template-columns:repeat(auto-fill,minmax(400rpx,1fr) )  ;
		.item_box:hover{
			background-color: #f4f6ff;
			transition:.5s;
		}
		.item_box{
			transition:.5s;
			cursor:pointer;
			margin:8px;
			text-align: center;
			padding:5px 0 0 0;
			border:1px solid #eee;
			border-radius:10px;
			.title{
				font-weight:bold;
				overflow:hidden;
				text-overflow: ellipsis;
				display:-webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
			}
			.label{
				line-height:30px;
				font-size:14px;
				color:#999;
				overflow:hidden;
				text-overflow: ellipsis;
				display:-webkit-box;
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
			}
		}
	}
	.similar_goods {
		border: 1px solid #ccc;
		width:90%;
		background: #fff;
		margin: -10px 0px 0px 0px;
		z-index: 9;
		box-shadow: 0 3px 20px 0 #eee;
		border-radius: 5px;
		position: absolute;
		.similar_goods_body{
			min-height: 100px;
			max-height:400px;
			overflow: auto;
			box-shadow: 1px 5px 20px 1px #eee;
		}
		.similar_goods_title_fixed{
			color: #999;
			padding:10px 30px;
			background:#fff; 
			font-size:14px;	font-weight: bold;
			display: flex;	justify-content: space-between;
		}
	}

	.goods-add-attr:hover {
		background: rgba(255, 229, 100, .3)
	}
	.goods-add-attr {
		width: calc(100% - 100px);
		height: 30px;
		line-height: 30px;
		text-align: center;
		background: rgba(240, 240, 240, .3);
		color: #e7c000;
		margin-bottom: 20px;
		font-size: 13px;
		cursor: pointer;
		border: 1px solid #e7c000;
		margin-left: 100px;
	}

	.add-goods-sku {
		margin-top: 10px;
	}

	.goods-add-sku-del {
		width: 60px;
		height: 30px;
		line-height: 30px;
		text-align: center;
		border: 1px solid #ccc;
		color: #666;
		border-radius: 3px;
		float: left;
		margin-left: calc((100% - 60px)/2)
	}

	.table--border {
		min-height: 100px;
	}
</style>